package com.barneyx.mshinfoplatform.common;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.barneyx.mshinfoplatform.exception.SmsException;
import com.barneyx.mshinfoplatform.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;

import static com.barneyx.mshinfoplatform.common.ExResult.ResponseCode.SMS_OFFICE_ERROR;

@Component
@Slf4j
public class SmsUtil {
    @Value("${alibaba.sms.sms-access-key-id}")
    private String smsAccessKeyId;
    @Value("${alibaba.sms.sms-access-key-secret}")
    private String smsAccessKeySecret;

    @Value("${alibaba.sms.sms-endpoint}")
    private String smsEndpoint;
    @Value("${alibaba.sms.sms-sign-name}")
    private String smsSignName;
    @Value("${alibaba.sms.sms-template-code}")
    private String smsTemplateCode;

    @Resource
    private RedisUtil redisUtil;

    private final String MSH_IS_SEND_FLAG = "MSH_IS_SEND_FLAG_";
    private final String MSH_VALID_PHONE = "MSH_VALID_PHONE_";

    public Boolean getSendFlag(String phone) {
        return redisUtil.get(MSH_IS_SEND_FLAG + phone) != null;
    }

    public void setSendFlag(String phone) {
        redisUtil.set(MSH_IS_SEND_FLAG + phone, phone, 60);
    }

    public String getValidPhone(String phone) {
        return (String) redisUtil.get(MSH_VALID_PHONE + phone);
    }

    public String setValidPhone(String phone) {
        String code = RandomUtil.randomNumbers(4);
        redisUtil.set(MSH_VALID_PHONE + phone, code, 60 * 30);
        return code;
    }

    public String redisSetCode(String phone) throws SmsException {
        if (getSendFlag(phone)) throw new SmsException(SMS_OFFICE_ERROR);
        setSendFlag(phone);
        return setValidPhone(phone);
    }


    public boolean sendVerificationBindPhoneCode(String phone) throws SmsException {
        String code = redisSetCode(phone);
        log.error("调试验证码:" + code);

        DefaultProfile profile = DefaultProfile.getProfile("default", smsAccessKeyId, smsAccessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("PhoneNumbers", phone);                    //手机号
        request.putQueryParameter("SignName", smsSignName);    //申请阿里云 签名名称（暂时用阿里云测试的，自己还不能注册签名）
        request.putQueryParameter("TemplateCode", smsTemplateCode); //申请阿里云 模板code（用的也是阿里云测试的）
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(MapUtil.builder(new HashMap<String, String>())
                .put("code", code).build()));

        try {
            CommonResponse response = client.getCommonResponse(request);
            return response.getHttpResponse().isSuccess();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


}
